<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { useRoute } from "vue-router";
  import axios from '@/utils/axios';
  import { showToast, showImagePreview } from "vant";
  import PostDetailsComment from './PostDetails-Comment.vue';

  const route = useRoute();
  const postId = ref(route.params.postId);
  const isLoading = ref(true);
  // 添加关注状态
  const isFollowing = ref(false);

  const data = reactive({
    follows:{
      followeeId:0,
    },
    post: {
      postId: 0,
      title: "",
      content: "",
      likeCount: 0,
      commentCount: 0,
      collectCount: 0,
      publishTime: "",
      user: { avatar: "", nickname: "", level: 1 },
      games: { gameName: '', gameId: 0 },
      postImages: [{ imageUrl: '' }],
      postTags: [{tagId: 0,tags: {tagName: ''}}],
    }
  });

  // 初始化帖子数据
  const fetchPostData = async () => {
    try {
      isLoading.value = true;
      const postId = route.params.postId;
      const res = await axios.post(`/api/hotStop/getByPostId/${postId}`);
      data.post = res.data;
      data.follows.followeeId = data.post.user.userId;
    } catch (err) {
      console.error("获取帖子详情失败:", err);
      showToast("加载失败，请重试");
    } finally {
      isLoading.value = false;
      axios.post("/api/hotStop/isFollowed",data.follows)
          .then(res => {
            if (res.data === 0) {
              isFollowing.value = true;
            } else {
              isFollowing.value = false;
            }
          })
    }
  };

  // 时间格式化函数
  const formatTime = (timestamp: string): string => {
    const now = new Date();
    const postTime = new Date(timestamp);
    const diffInHours = (now.getTime() - postTime.getTime()) / (1000 * 60 * 60);

    if (diffInHours < 1) {
      return `${Math.floor(diffInHours * 60)}分钟前`;
    }
    if (diffInHours < 24) {
      return `${Math.floor(diffInHours)}小时前`;
    }
    if (diffInHours < 48) {
      return `昨天 ${postTime.getHours().toString().padStart(2, '0')}:${postTime.getMinutes().toString().padStart(2, '0')}`;
    }
    if (postTime.getFullYear() === now.getFullYear()) {
      return `${postTime.getMonth() + 1}-${postTime.getDate()}`;
    }
    return `${postTime.getFullYear()}-${postTime.getMonth() + 1}-${postTime.getDate()}`;
  };

  // 预览图片
  const previewImage = (index: number) => {
    const images = data.post.postImages.map(img => img.imageUrl);
    showImagePreview({
      images,
      startPosition: index,
    });
  };

  // 处理图片加载错误
  const handleImageError = (event: Event) => {
    const target = event.target as HTMLImageElement;
    // 检查是否已经设置过默认图片，避免无限循环
    if (!target.src.includes('default')) {
      target.src = '/default-image.png';
    }
  };

  // 处理头像加载错误
  const handleAvatarError = (event: Event) => {
    const target = event.target as HTMLImageElement;
    // 检查是否已经设置过默认头像，避免无限循环
    if (!target.src.includes('default')) {
      target.src = '/default-avatar.png';
    }
  };

  onMounted(() => {
    fetchPostData();
  });

  // 关注和取消关注的方法
  const toggleFollow = () => {
    isFollowing.value = !isFollowing.value;
    axios.post("/api/hotStop/isFollowedChange",data.follows)
  };

</script>

<template>
  <div class="post-detail-container">
    <!-- 加载状态 -->
    <van-loading v-if="isLoading" class="page-loading" type="spinner" color="#1989fa" />

    <template v-else>
      <!-- 轮播图 -->
      <van-swipe
          v-if="data.post.postImages && data.post.postImages.length > 0"
          class="swipe-container"
          :loop="data.post.postImages.length > 1"
          @click-item="previewImage"
      >
        <van-swipe-item v-for="(image, index) in data.post.postImages" :key="index">
          <img
              :src="image.imageUrl"
              class="swipe-image"
              @error="handleImageError"
          />
        </van-swipe-item>
      </van-swipe>

      <!-- 头部区域 -->
      <div class="post-header">
        <h1 class="post-title">{{ data.post.title }}</h1>

        <div class="author-info">
          <img
              :src="data.post.user.avatar || '/default-avatar.png'"
              alt="用户头像"
              class="author-avatar"
              @error="handleAvatarError"
          >
          <div class="author-meta">
            <div class="author-name">
              {{ data.post.user.nickname || '匿名用户' }}
              <span class="user-level">Lv.{{data.post.user.level}}</span>
            </div>
            <div class="post-time">
              {{ formatTime(data.post.publishTime) }} · 上海
            </div>
          </div>
          <el-button
              :type="isFollowing ? 'primary' : 'default'"
              plain
              size="small"
              class="follow-btn"
              @click="toggleFollow"

          >
            {{ isFollowing ? '已关注' : '关注' }}
          </el-button>
        </div>

        <!-- 标签区域 -->
        <div class="tags-container" v-if="data.post.games.gameName || (data.post.postTags && data.post.postTags.length)">
          <!--游戏社区跳转-->
          <router-link
              :to="{ name: '', params: { gameId: data.post.games.gameId} }"
          >
            <span class="game-tag">{{ data.post.games.gameName }}</span>
          </router-link>

          <span
              v-for="tag in data.post.postTags"
              :key="tag.tagId"
              class="post-tag"
          >
              <!--话题社区跳转-->
            <router-link
                :to="{ name: '', params: { tagId: tag.tagId} }"
            >
              #{{ tag.tags.tagName }}
            </router-link>
          </span>

        </div>
      </div>

      <!-- 内容区域 -->
      <div class="post-content">
        <p class="content-text" v-html="data.post.content.replace(/\n/g, '<br>')"></p>

        <!-- 图片展示区（多图时） -->
        <div
            class="image-gallery"
            v-if="data.post.postImages && data.post.postImages.length > 1"
        >
          <div
              v-for="(img, index) in data.post.postImages"
              :key="index"
              class="image-item"
              @click="previewImage(index)"
          >
            <img
                :src="img.imageUrl"
                :alt="`图片 ${index + 1}`"
                class="content-image"
                @error="handleImageError"
            />
          </div>
        </div>
      </div>

      <van-divider class="content-divider" />
    </template>

    <!-- 评论组件 -->
    <PostDetailsComment :post-id="postId" />
  </div>
</template>

<style scoped>
  .page-loading {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
  }

  .post-detail-container {
    background-color: #fff;
    color: #333;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }

  .swipe-container {
    height: 280px;
    width: 100%;
    overflow: hidden;
  }

  .swipe-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .swipe-image:hover {
    transform: scale(1.02);
  }

  .post-header {
    padding: 18px 15px 10px;
  }

  .post-title {
    font-size: 20px;
    font-weight: 600;
    line-height: 1.4;
    margin: 0 0 15px;
    color: #1a1a1a;
  }

  .author-info {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }

  .author-avatar {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 12px;
    border: 1px solid #f0f0f0;
  }

  .author-meta {
    flex: 1;
  }

  .author-name {
    font-size: 15px;
    font-weight: 500;
    color: #333;
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 3px;
  }

  .user-level {
    font-size: 12px;
    color: #999;
    background-color: #f5f5f5;
    padding: 1px 6px;
    border-radius: 10px;
  }

  .post-time {
    font-size: 12px;
    color: #999;
  }

  .follow-btn {
    min-width: 70px;
    height: 32px;
    line-height: 30px;
    border-radius: 16px;
    font-size: 14px;
    padding: 0 12px;
  }

  /* 确保 Element Plus 主题一致性 */
  :deep(.el-button--primary) {
    --el-button-bg-color: var(--el-color-primary);
    --el-button-border-color: var(--el-color-primary);
    --el-button-text-color: #fff;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
    padding-bottom: 5px;
  }

  .game-tag {
    background-color: #f0f5ff;
    color: #4096ff;
  }

  .post-tag {
    background-color: #f5f5f5;
    color: #666;
  }

  .game-tag, .post-tag {
    font-size: 12px;
    padding: 3px 10px;
    border-radius: 12px;
    white-space: nowrap;
  }

  .post-content {
    padding: 10px 15px 15px;
  }

  .content-text {
    font-size: 16px;
    line-height: 1.8;
    color: #333;
    margin: 0 0 15px;
    word-break: break-word;
  }

  .image-gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 8px;
    margin-top: 15px;
  }

  .image-item {
    border-radius: 8px;
    overflow: hidden;
    aspect-ratio: 1/1;
    cursor: pointer;
    position: relative;
  }

  .content-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .image-item:hover .content-image {
    transform: scale(1.05);
  }

  .content-divider {
    margin: 15px 0;
    background-color: #f5f5f5;
  }
</style>
